#include "EzToastWidget.h"

#include <QGuiApplication>
#include <QHBoxLayout>
#include <QPainter>
#include <QPropertyAnimation>
#include <QScreen>

// 颜色常量
const int IconSize = 20;
const int ButtonSize = 20;
const int CornerRadius = 6;

// 背景与边框颜色
const QString DefaultBackgroundColor = "#f0f5ff";  // 淡蓝色背景
const QString DefaultBorderColor = "#adc6ff";      // 浅蓝边框
const QString DefaultFontColor = "#1d1d1f";        // 深灰色字体

// 关闭按钮样式
const QString CloseButtonStyle = R"(
    QPushButton {
        background-color: transparent;
        color: #666;       /* 默认灰色 */
        border: none;
        font-size: 16px;
        padding: 0;
    }
    QPushButton:hover {
        color: #333;       /* 悬停时更深的灰色 */
    }
)";

// 信息ICON
const QString base64InfoIconData =
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAfZJREFUWEfFlztLw1AUx/"
    "+nKLqkCroqjS6uglVXlw4uOgj6EWxacFD8EKKD0IcfQcFBFwcXV7UFVxdNsasFbRal0iNJm5KkaXNvUsidAjmP373ncc8lxLwoZv+"
    "QAkhdNLeIKQPmNEALAGa6G2gA/A6iChPf1/aTt6IbEwJQi81DEB0AmBM0XAfzuZ5LngXJDwVIFb7XiKgAopUgQ77/mavMnK/"
    "lp54G6Q8ESBWNXSJchnLsUWLGXi2nXPnZ8gUYpXPb6SCIPgDr2BOJx1Hs3GuD2+11bzj6ANRisxI65kHUzFU9l0w7xVwA3Ww/DbJj/"
    "lenE8guj1ui5ZcW9K+2iBrAfOSsDjdAyfgQLbWTjQnsLHUArl9bOH74FQMA6rqmzNvCPQCrybTpRtRKBABwgrftZtUDUMtGEQxNFCB0CEwHhJKeVXKdz+"
    "5SS81ngFwJIgojL8cVXUuuegCMT0dvD7S5uTjmkrl7+wvUcQg0dE2Z9QKwjAUToJCZtFTy9z+QBICuKdbpO0JgxA4gHYIIJ+"
    "AXArkkjBYCvySULMNIAH5lKNuIogD4NiKrv0u04ggA/q3YAuiMXkKXkUzJumSHXUZdiPiuYxMg9oHEghjhPGgfv/"
    "BIZiuMEkJ6KO1BxDmWOzM3toeJt9Rie5qFrnkBRaG3oYCd0CL/QcMTMES0Ks4AAAAASUVORK5CYII=";

EzToastWidget* EzToastWidget::instance()
{
    static EzToastWidget toast;
    return &toast;
}

EzToastWidget::EzToastWidget(QWidget* parent)
    : QWidget(parent)
    , m_backgroundColor(DefaultBackgroundColor)
    , m_borderColor(DefaultBorderColor)
    , m_fontColor(DefaultFontColor)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_ShowWithoutActivating);

    QHBoxLayout* mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(10, 5, 10, 5);
    mainLayout->setSpacing(10);

    m_iconLabel = new QLabel(this);
    QByteArray byteArray = QByteArray::fromBase64(base64InfoIconData.toUtf8());
    QPixmap pixmap;
    pixmap.loadFromData(byteArray);
    m_iconLabel->setPixmap(pixmap.scaled(IconSize, IconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    m_label = new QLabel(this);
    applyLabelStyle();

    m_closeButton = new QPushButton("×", this);
    m_closeButton->setStyleSheet(CloseButtonStyle);
    m_closeButton->setFixedSize(ButtonSize, ButtonSize);
    m_closeButton->setCursor(Qt::PointingHandCursor);
    connect(m_closeButton, &QPushButton::clicked, this, &EzToastWidget::closeToast);

    mainLayout->addWidget(m_iconLabel);
    mainLayout->addWidget(m_label, 1);
    mainLayout->addWidget(m_closeButton);

    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &EzToastWidget::fadeOut);

    hide();
}

void EzToastWidget::showMessage(const QString& message, int duration, bool autoClose)
{
    m_label->setText(message);
    adjustSize();  // 重新调整大小
    fadeIn();
    if (autoClose) {
        m_timer->start(duration);
        m_closeButton->hide();
    } else {
        m_timer->stop();
        m_closeButton->show();
    }
}

void EzToastWidget::setIcon(const QPixmap& icon)
{
    m_iconLabel->setPixmap(icon.scaled(IconSize, IconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
}

void EzToastWidget::setBackgroundColor(const QColor& color)
{
    if (m_backgroundColor != color) {
        m_backgroundColor = color;
        update();
    }
}

void EzToastWidget::setBorderColor(const QColor& color)
{
    if (m_borderColor != color) {
        m_borderColor = color;
        update();
    }
}

void EzToastWidget::setFontColor(const QColor& color)
{
    if (m_fontColor != color) {
        m_fontColor = color;
        applyLabelStyle();
    }
}

void EzToastWidget::applyLabelStyle()
{
    m_label->setStyleSheet(QString("QLabel { color: %1; font-size: 14px; }").arg(m_fontColor.name()));
}

void EzToastWidget::mousePressEvent(QMouseEvent* event)
{
    Q_UNUSED(event);
    fadeOut();  // 点击窗口任意位置触发关闭动画
}

void EzToastWidget::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    updatePosition(m_showRect);
}

void EzToastWidget::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    painter.setBrush(m_backgroundColor);
    painter.setPen(QPen(m_borderColor, 1));
    QRect rect = this->rect();
    painter.drawRoundedRect(rect, CornerRadius, CornerRadius);
}

void EzToastWidget::fadeIn()
{
    setWindowOpacity(0.0);
    show();
    QPropertyAnimation* animation = new QPropertyAnimation(this, "windowOpacity");
    animation->setDuration(200);
    animation->setStartValue(0.0);
    animation->setEndValue(1.0);
    animation->setEasingCurve(QEasingCurve::InOutQuad);
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void EzToastWidget::fadeOut()
{
    QPropertyAnimation* animation = new QPropertyAnimation(this, "windowOpacity");
    animation->setDuration(200);
    animation->setStartValue(1.0);
    animation->setEndValue(0.0);
    animation->setEasingCurve(QEasingCurve::InOutQuad);
    connect(animation, &QPropertyAnimation::finished, this, &EzToastWidget::close);
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void EzToastWidget::closeToast()
{
    fadeOut();  // 使用淡出动画关闭
}

void EzToastWidget::updatePosition(const QRect& targetRect)
{
    m_showRect = targetRect;
    // 将 Toast 显示在目标矩形右下角
    int x = targetRect.x() + targetRect.width() - width() - 5;
    int y = targetRect.y() - height() - 5;
    move(x, y);
}
